0012. tsc 快速入门
- 1. 🎯 本节内容
- 2. 🫧 评价
- 3. 🤔 tsc 是什么?
- 4. 🤔 如何安装和验证 tsc 编译器?
- 5. 🤔 如何获取 tsc 命令的帮助信息?
- 6. 🤔 如何使用 tsc 编译单个或多个 TypeScript 文件?
- 7. 🤔 tsc 有哪些常用的编译选项?
- 8. 🤔 TypeScript 编译出错时会发生什么?
- 9. 🤔 如何使用 tsconfig.json 配置文件?
- 10. 🤔 tsconfig.json 配置文件的作用是什么?
- 11. 🤔 tsconfig.json 和 tsc 之间的关系是?
1. 🎯 本节内容
- tsc
- tsconfig.json
2. 🫧 评价
- 本节主要对 tsc 和 tsconfig.json 做一个简单的介绍,接下来的学习过程中会接触到 ts 配置和 ts 编译相关的知识点。
- 对于 tsc 和 tsconfig.json 的具体细节,比如都有哪些配置,每个配置的具体作用,会在后续内容中详细介绍。
3. 🤔 tsc 是什么?
- tsc 是 TypeScript Compiler 的缩写,是 TypeScript 官方提供的编译器工具。它的主要作用是将 TypeScript 代码编译成 JavaScript 代码,使 TypeScript 能够在各种 JavaScript 运行环境中执行。
- TypeScript 是 JavaScript 的超集,添加了静态类型检查等功能,但浏览器和 Node.js 等环境无法直接执行 TypeScript 代码,因此需要使用 tsc 将其编译为标准的 JavaScript 代码。
- tsc 不仅仅是一个简单的编译器,它还提供了丰富的编译选项和配置功能,允许开发者根据项目需求定制编译行为,如指定目标 JavaScript 版本、模块系统、输出目录等。
4. 🤔 如何安装和验证 tsc 编译器?
- tsc 是 TypeScript 官方提供的编译器,需要通过 npm 进行安装。可以使用以下命令全局安装:
bash
npm install -g typescript
# 安装 typescript 会自动安装它的编译器 tsc1
2
2
- 安装完成后,可以通过以下命令验证是否安装成功:
bash
tsc -v
# 或者
tsc --version1
2
3
2
3
- 示例:

5. 🤔 如何获取 tsc 命令的帮助信息?
- tsc 提供了帮助命令来查看可用选项:
bash
tsc -h
# 或者
tsc --help1
2
3
2
3
输出示例
bash
$ tsc -h
tsc: The TypeScript Compiler - Version 5.3.3
TS
COMMON COMMANDS
tsc
Compiles the current project (tsconfig.json in the working directory.)
tsc app.ts util.ts
Ignoring tsconfig.json, compiles the specified files with default compiler options.
tsc -b
Build a composite project in the working directory.
tsc --init
Creates a tsconfig.json with the recommended settings in the working directory.
tsc -p ./path/to/tsconfig.json
Compiles the TypeScript project located at the specified path.
tsc --help --all
An expanded version of this information, showing all possible compiler options
tsc --noEmit
tsc --target esnext
Compiles the current project, with additional settings.
COMMAND LINE FLAGS
--help, -h Print this message.
--watch, -w Watch input files.
--all Show all compiler options.
--version, -v Print the compiler's version.
--init Initializes a TypeScript project and creates a tsconfig.json file.
--project, -p Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'.
--build, -b Build one or more projects and their dependencies, if out of date
--showConfig Print the final configuration instead of building.
COMMON COMPILER OPTIONS
--pretty Enable color and formatting in TypeScript's output to make compiler errors easier to read.
type: boolean
default: true
--declaration, -d Generate .d.ts files from TypeScript and JavaScript files in your project.
type: boolean
default: `false`, unless `composite` is set
--declarationMap Create sourcemaps for d.ts files.
type: boolean
default: false
--emitDeclarationOnly Only output d.ts files and not JavaScript files.
type: boolean
default: false
--sourceMap Create source map files for emitted JavaScript files.
type: boolean
default: false
--target, -t Set the JavaScript language version for emitted JavaScript and include comp atible library declarations.
one of: es3, es5, es6/es2015, es2016, es2017, es2018, es2019, es2020, es2021, es202 2, esnext
default: es5
--module, -m Specify what module code is generated.
one of: none, commonjs, amd, umd, system, es6/es2015, es2020, es2022, esnext, node1 6, nodenext
default: undefined
--lib Specify a set of bundled library declaration files that describe the target runtime environment.
one or more: es5, es6/es2015, es7/es2016, es2017, es2018, es2019, es2020, es2021, es2022 , es2023, esnext, dom, dom.iterable, webworker, webworker.importscripts, we bworker.iterable, scripthost, es2015.core, es2015.collection, es2015.genera tor, es2015.iterable, es2015.promise, es2015.proxy, es2015.reflect, es2015. symbol, es2015.symbol.wellknown, es2016.array.include, es2017.date, es2017. object, es2017.sharedmemory, es2017.string, es2017.intl, es2017.typedarrays , es2018.asyncgenerator, es2018.asynciterable/esnext.asynciterable, es2018. intl, es2018.promise, es2018.regexp, es2019.array, es2019.object, es2019.st ring, es2019.symbol/esnext.symbol, es2019.intl, es2020.bigint/esnext.bigint , es2020.date, es2020.promise, es2020.sharedmemory, es2020.string, es2020.s ymbol.wellknown, es2020.intl, es2020.number, es2021.promise/esnext.promise, es2021.string, es2021.weakref/esnext.weakref, es2021.intl, es2022.array, e s2022.error, es2022.intl, es2022.object, es2022.sharedmemory, es2022.string /esnext.string, es2022.regexp, es2023.array/esnext.array, es2023.collection /esnext.collection, esnext.intl, esnext.disposable, esnext.decorators, deco rators, decorators.legacy
default: undefined
--allowJs Allow JavaScript files to be a part of your program. Use the 'checkJS' opti on to get errors from these files.
type: boolean
default: false
--checkJs Enable error reporting in type-checked JavaScript files.
type: boolean
default: false
--jsx Specify what JSX code is generated.
one of: preserve, react, react-native, react-jsx, react-jsxdev
default: undefined
--outFile Specify a file that bundles all outputs into one JavaScript file. If 'decla ration' is true, also designates a file that bundles all .d.ts output.
--outDir Specify an output folder for all emitted files.
--removeComments Disable emitting comments.
type: boolean
default: false
--noEmit Disable emitting files from a compilation.
type: boolean
default: false
--strict Enable all strict type-checking options.
type: boolean
default: false
--types Specify type package names to be included without being referenced in a sou rce file.
--esModuleInterop Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility.
type: boolean
default: false
You can learn about all of the compiler options at https://aka.ms/tsc1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
- 如果需要查看完整的帮助信息,可以使用:
bash
tsc --all1
输出示例
bash
$ tsc --all
tsc: The TypeScript Compiler - Version 5.3.3
TS
ALL COMPILER OPTIONS
### Command-line Options
--all Show all compiler options.
--build, -b Build one or more projects and their dependencies, if out of date
--help, -h Print this message.
--init Initializes a TypeScript project and creates a tsconfig.json file.
--listFilesOnly Print names of files that are part of the compilation and then stop processing.
--locale Set the language of the messaging from TypeScript. This does not affect emit.
--project, -p Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'.
--showConfig Print the final configuration instead of building.
--version, -v Print the compiler's version.
--watch, -w Watch input files.
### Modules
--allowArbitraryExtensions Enable importing files with any extension, provided a declaration fi le is present.
type: boolean
default: false
--allowImportingTsExtensions Allow imports to include TypeScript file extensions. Requires '--mod uleResolution bundler' and either '--noEmit' or '--emitDeclarationOn ly' to be set.
type: boolean
default: false
--allowUmdGlobalAccess Allow accessing UMD globals from modules.
type: boolean
default: false
--baseUrl Specify the base directory to resolve non-relative module names.
--customConditions Conditions to set in addition to the resolver-specific defaults when resolving imports.
--module, -m Specify what module code is generated.
one of: none, commonjs, amd, umd, system, es6/es2015, es2020, es2022, esnext , node16, nodenext
default: undefined
--moduleResolution Specify how TypeScript looks up a file from a given module specifier .
one of: classic, node10/node, node16, nodenext, bundler
default: module === `AMD` or `UMD` or `System` or `ES6`, then `Classic`, Othe rwise `Node`
--moduleSuffixes List of file name suffixes to search when resolving a module.
--noResolve Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project.
type: boolean
default: false
--paths Specify a set of entries that re-map imports to additional lookup lo cations.
default: undefined
--resolveJsonModule Enable importing .json files.
type: boolean
default: false
--resolvePackageJsonExports Use the package.json 'exports' field when resolving package imports.
type: boolean
default: `true` when 'moduleResolution' is 'node16', 'nodenext', or 'bundler' ; otherwise `false`.
--resolvePackageJsonImports Use the package.json 'imports' field when resolving imports.
type: boolean
default: `true` when 'moduleResolution' is 'node16', 'nodenext', or 'bundler' ; otherwise `false`.
--rootDir Specify the root folder within your source files.
type: string
default: Computed from the list of input files
--rootDirs Allow multiple folders to be treated as one when resolving modules.
one or more: string
default: Computed from the list of input files
--typeRoots Specify multiple folders that act like './node_modules/@types'.
--types Specify type package names to be included without being referenced i n a source file.
### JavaScript Support
--allowJs Allow JavaScript files to be a part of your program. Use the 'checkJS' opt ion to get errors from these files.
type: boolean
default: false
--checkJs Enable error reporting in type-checked JavaScript files.
type: boolean
default: false
--maxNodeModuleJsDepth Specify the maximum folder depth used for checking JavaScript files from ' node_modules'. Only applicable with 'allowJs'.
type: number
default: 0
### Interop Constraints
--allowSyntheticDefaultImports Allow 'import x from y' when a module doesn't have a default e xport.
type: boolean
default: module === "system" or esModuleInterop
--esModuleInterop Emit additional JavaScript to ease support for importing Commo nJS modules. This enables 'allowSyntheticDefaultImports' for t ype compatibility.
type: boolean
default: false
--forceConsistentCasingInFileNames Ensure that casing is correct in imports.
type: boolean
default: true
--isolatedModules Ensure that each file can be safely transpiled without relying on other imports.
type: boolean
default: false
--preserveSymlinks Disable resolving symlinks to their realpath. This correlates to the same flag in node.
type: boolean
default: false
--verbatimModuleSyntax Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's for mat based on the 'module' setting.
type: boolean
default: false
### Type Checking
--allowUnreachableCode Disable error reporting for unreachable code.
type: boolean
default: undefined
--allowUnusedLabels Disable error reporting for unused labels.
type: boolean
default: undefined
--alwaysStrict Ensure 'use strict' is always emitted.
type: boolean
default: `false`, unless `strict` is set
--exactOptionalPropertyTypes Interpret optional property types as written, rather than ad ding 'undefined'.
type: boolean
default: false
--noFallthroughCasesInSwitch Enable error reporting for fallthrough cases in switch state ments.
type: boolean
default: false
--noImplicitAny Enable error reporting for expressions and declarations with an implied 'any' type.
type: boolean
default: `false`, unless `strict` is set
--noImplicitOverride Ensure overriding members in derived classes are marked with an override modifier.
type: boolean
default: false
--noImplicitReturns Enable error reporting for codepaths that do not explicitly return in a function.
type: boolean
default: false
--noImplicitThis Enable error reporting when 'this' is given the type 'any'.
type: boolean
default: `false`, unless `strict` is set
--noPropertyAccessFromIndexSignature Enforces using indexed accessors for keys declared using an indexed type.
type: boolean
default: false
--noUncheckedIndexedAccess Add 'undefined' to a type when accessed using an index.
type: boolean
default: false
--noUnusedLocals Enable error reporting when local variables aren't read.
type: boolean
default: false
--noUnusedParameters Raise an error when a function parameter isn't read.
type: boolean
default: false
--strict Enable all strict type-checking options.
type: boolean
default: false
--strictBindCallApply Check that the arguments for 'bind', 'call', and 'apply' met hods match the original function.
type: boolean
default: `false`, unless `strict` is set
--strictFunctionTypes When assigning functions, check to ensure parameters and the return values are subtype-compatible.
type: boolean
default: `false`, unless `strict` is set
--strictNullChecks When type checking, take into account 'null' and 'undefined' .
type: boolean
default: `false`, unless `strict` is set
--strictPropertyInitialization Check for class properties that are declared but not set in the constructor.
type: boolean
default: `false`, unless `strict` is set
--useUnknownInCatchVariables Default catch clause variables as 'unknown' instead of 'any' .
type: boolean
default: `false`, unless `strict` is set
### Watch and Build Modes
--assumeChangesOnlyAffectDirectDependencies Have recompiles in projects that use 'incremental' an d 'watch' mode assume that changes within a file will only affect files directly depending on it.
type: boolean
default: false
### Backwards Compatibility
--charset No longer supported. In early versions, manually set the text en coding for reading files.
type: string
default: utf8
--keyofStringsOnly Make keyof only return strings instead of string, numbers or sym bols. Legacy option.
type: boolean
default: false
--noImplicitUseStrict Disable adding 'use strict' directives in emitted JavaScript fil es.
type: boolean
default: false
--noStrictGenericChecks Disable strict checking of generic signatures in function types.
type: boolean
default: false
--out Deprecated setting. Use 'outFile' instead.
--suppressExcessPropertyErrors Disable reporting of excess property errors during the creation of object literals.
type: boolean
default: false
--suppressImplicitAnyIndexErrors Suppress 'noImplicitAny' errors when indexing objects that lack index signatures.
type: boolean
default: false
### Projects
--composite Enable constraints that allow a TypeScript project to b e used with project references.
type: boolean
default: false
--disableReferencedProjectLoad Reduce the number of projects loaded automatically by T ypeScript.
type: boolean
default: false
--disableSolutionSearching Opt a project out of multi-project reference checking w hen editing.
type: boolean
default: false
--disableSourceOfProjectReferenceRedirect Disable preferring source files instead of declaration files when referencing composite projects.
type: boolean
default: false
--incremental, -i Save .tsbuildinfo files to allow for incremental compil ation of projects.
type: boolean
default: `false`, unless `composite` is set
--tsBuildInfoFile Specify the path to .tsbuildinfo incremental compilatio n file.
type: string
default: .tsbuildinfo
### Emit
--declaration, -d Generate .d.ts files from TypeScript and JavaScript files in your projec t.
type: boolean
default: `false`, unless `composite` is set
--declarationDir Specify the output directory for generated declaration files.
--declarationMap Create sourcemaps for d.ts files.
type: boolean
default: false
--downlevelIteration Emit more compliant, but verbose and less performant JavaScript for iter ation.
type: boolean
default: false
--emitBOM Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files.
type: boolean
default: false
--emitDeclarationOnly Only output d.ts files and not JavaScript files.
type: boolean
default: false
--importHelpers Allow importing helper functions from tslib once per project, instead of including them per-file.
type: boolean
default: false
--importsNotUsedAsValues Specify emit/checking behavior for imports that are only used for types.
one of: remove, preserve, error
default: remove
--inlineSourceMap Include sourcemap files inside the emitted JavaScript.
type: boolean
default: false
--inlineSources Include source code in the sourcemaps inside the emitted JavaScript.
type: boolean
default: false
--mapRoot Specify the location where debugger should locate map files instead of g enerated locations.
--newLine Set the newline character for emitting files.
one of: crlf, lf
--noEmit Disable emitting files from a compilation.
type: boolean
default: false
--noEmitHelpers Disable generating custom helper functions like '__extends' in compiled output.
type: boolean
default: false
--noEmitOnError Disable emitting files if any type checking errors are reported.
type: boolean
default: false
--outDir Specify an output folder for all emitted files.
--outFile Specify a file that bundles all outputs into one JavaScript file. If 'de claration' is true, also designates a file that bundles all .d.ts output .
--preserveConstEnums Disable erasing 'const enum' declarations in generated code.
type: boolean
default: false
--preserveValueImports Preserve unused imported values in the JavaScript output that would othe rwise be removed.
type: boolean
default: false
--removeComments Disable emitting comments.
type: boolean
default: false
--sourceMap Create source map files for emitted JavaScript files.
type: boolean
default: false
--sourceRoot Specify the root path for debuggers to find the reference source code.
--stripInternal Disable emitting declarations that have '@internal' in their JSDoc comme nts.
type: boolean
default: false
### Compiler Diagnostics
--diagnostics Output compiler performance information after building.
type: boolean
default: false
--explainFiles Print files read during the compilation including why it was included.
type: boolean
default: false
--extendedDiagnostics Output more detailed compiler performance information after building.
type: boolean
default: false
--generateCpuProfile Emit a v8 CPU profile of the compiler run for debugging.
type: string
default: profile.cpuprofile
--generateTrace Generates an event trace and a list of types.
--listEmittedFiles Print the names of emitted files after a compilation.
type: boolean
default: false
--listFiles Print all of the files read during the compilation.
type: boolean
default: false
--traceResolution Log paths used during the 'moduleResolution' process.
type: boolean
default: false
### Editor Support
--disableSizeLimit Remove the 20mb cap on total source code size for JavaScript files in the Type Script language server.
type: boolean
default: false
--plugins Specify a list of language service plugins to include.
default: undefined
### Language and Environment
--emitDecoratorMetadata Emit design-type metadata for decorated declarations in source files.
type: boolean
default: false
--experimentalDecorators Enable experimental support for legacy experimental decorators.
type: boolean
default: false
--jsx Specify what JSX code is generated.
one of: preserve, react, react-native, react-jsx, react-jsxdev
default: undefined
--jsxFactory Specify the JSX factory function used when targeting React JSX emit, e. g. 'React.createElement' or 'h'.
type: string
default: `React.createElement`
--jsxFragmentFactory Specify the JSX Fragment reference used for fragments when targeting Re act JSX emit e.g. 'React.Fragment' or 'Fragment'.
type: string
default: React.Fragment
--jsxImportSource Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'.
type: string
default: react
--lib Specify a set of bundled library declaration files that describe the ta rget runtime environment.
one or more: es5, es6/es2015, es7/es2016, es2017, es2018, es2019, es2020, es2021, es 2022, es2023, esnext, dom, dom.iterable, webworker, webworker.importscr ipts, webworker.iterable, scripthost, es2015.core, es2015.collection, e s2015.generator, es2015.iterable, es2015.promise, es2015.proxy, es2015. reflect, es2015.symbol, es2015.symbol.wellknown, es2016.array.include, es2017.date, es2017.object, es2017.sharedmemory, es2017.string, es2017. intl, es2017.typedarrays, es2018.asyncgenerator, es2018.asynciterable/e snext.asynciterable, es2018.intl, es2018.promise, es2018.regexp, es2019 .array, es2019.object, es2019.string, es2019.symbol/esnext.symbol, es20 19.intl, es2020.bigint/esnext.bigint, es2020.date, es2020.promise, es20 20.sharedmemory, es2020.string, es2020.symbol.wellknown, es2020.intl, e s2020.number, es2021.promise/esnext.promise, es2021.string, es2021.weak ref/esnext.weakref, es2021.intl, es2022.array, es2022.error, es2022.int l, es2022.object, es2022.sharedmemory, es2022.string/esnext.string, es2 022.regexp, es2023.array/esnext.array, es2023.collection/esnext.collect ion, esnext.intl, esnext.disposable, esnext.decorators, decorators, dec orators.legacy
default: undefined
--moduleDetection Control what method is used to detect module-format JS files.
one of: legacy, auto, force
default: "auto": Treat files with imports, exports, import.meta, jsx (with jsx: react-jsx), or esm format (with module: node16+) as modules.
--noLib Disable including any library files, including the default lib.d.ts.
type: boolean
default: false
--reactNamespace Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit.
type: string
default: `React`
--target, -t Set the JavaScript language version for emitted JavaScript and include compatible library declarations.
one of: es3, es5, es6/es2015, es2016, es2017, es2018, es2019, es2020, es2021, e s2022, esnext
default: es5
--useDefineForClassFields Emit ECMAScript-standard-compliant class fields.
type: boolean
default: `true` for ES2022 and above, including ESNext.
### Output Formatting
--noErrorTruncation Disable truncating types in error messages.
type: boolean
default: false
--preserveWatchOutput Disable wiping the console in watch mode.
type: boolean
default: false
--pretty Enable color and formatting in TypeScript's output to make compiler errors easier to read.
type: boolean
default: true
### Completeness
--skipDefaultLibCheck Skip type checking .d.ts files that are included with TypeScript.
type: boolean
default: false
--skipLibCheck Skip type checking all .d.ts files.
type: boolean
default: false
You can learn about all of the compiler options at https://aka.ms/tsc
WATCH OPTIONS
Including --watch, -w will start watching the current project for the file changes. Once set, you can config watch mode with:
--watchFile Specify how the TypeScript watch mode works.
one of: fixedpollinginterval, prioritypollinginterval, dynamicprioritypolling , fixedchunksizepolling, usefsevents, usefseventsonparentdirectory
default: usefsevents
--watchDirectory Specify how directories are watched on systems that lack recursive fi le-watching functionality.
one of: usefsevents, fixedpollinginterval, dynamicprioritypolling, fixedchunk sizepolling
default: usefsevents
--fallbackPolling Specify what approach the watcher should use if the system runs out o f native file watchers.
one of: fixedinterval, priorityinterval, dynamicpriority, fixedchunksize
default: priorityinterval
--synchronousWatchDirectory Synchronously call callbacks and update the state of directory watche rs on platforms that don`t support recursive watching natively.
type: boolean
default: false
--excludeDirectories Remove a list of directories from the watch process.
--excludeFiles Remove a list of files from the watch mode's processing.
BUILD OPTIONS
Using --build, -b will make tsc behave more like a build orchestrator than a compiler. This is used to trigger building composite projects which you can learn more about at https://aka.ms/tsc-composite-builds
--verbose, -v Enable verbose logging.
--dry, -d Show what would be built (or deleted, if specified with '--clean')
--force, -f Build all projects, including those that appear to be up to date.
--clean Delete the outputs of all projects.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
6. 🤔 如何使用 tsc 编译单个或多个 TypeScript 文件?
- 编译单个 TypeScript 文件非常简单,只需执行:
bash
tsc app.ts
# 这将在当前目录生成对应的 app.js 文件1
2
2
- 编译多个文件可以一次性指定多个文件:
bash
tsc file1.ts file2.ts file3.ts
# 这将分别生成 file1.js、file2.js 和 file3.js 文件1
2
2
7. 🤔 tsc 有哪些常用的编译选项?
- tsc 提供了多个编译选项来控制编译行为,这里先简单认识几个常用的:
bash
# --outFile 将多个 TypeScript 文件编译成一个 JavaScript 文件
tsc file1.ts file2.ts --outFile app.js
# --outDir 指定编译结果的输出目录
tsc app.ts --outDir dist
# --target 指定编译后的 JavaScript 版本
tsc --target es2015 app.ts
# --module 指定生成的模块系统类型
tsc --module commonjs app.ts
# --watch 或 -w 监听文件变化并自动重新编译
tsc --watch app.ts
# --strict 启用所有严格的类型检查选项
tsc --strict app.ts
# --lib 指定要包含在编译中的库文件
tsc --lib es2015,dom app.ts
# --declaration 生成相应的 .d.ts 声明文件
tsc --declaration app.ts
# --sourceMap 生成相应的 .map 文件,便于调试
tsc --sourceMap app.ts
# --noEmit 只进行类型检查,不生成输出文件
tsc --noEmit app.ts
# --esModuleInterop 允许从没有设置默认导出的模块中导入
tsc --esModuleInterop app.ts
# --allowJs 允许编译 JavaScript 文件
tsc --allowJs app.js
# --checkJs 报告 JavaScript 文件中的错误(与 --allowJs 配合使用)
tsc --allowJs --checkJs app.js1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
8. 🤔 TypeScript 编译出错时会发生什么?
- 当 TypeScript 代码存在类型错误时,
tsc命令会显示错误信息,但仍会生成 JavaScript 文件。例如:
ts
let foo: number = 123
foo = 'abc' // 类型错误1
2
2
- 编译时会显示错误信息,但仍然生成
app.js文件。 - 如果希望在出错时停止编译并不生成文件,可以使用:
bash
tsc --noEmitOnError app.ts1
- 如果只想检查类型错误而不生成文件,可以使用:
bash
tsc --noEmit app.ts1
9. 🤔 如何使用 tsconfig.json 配置文件?
- TypeScript 支持使用 tsconfig.json 文件来配置编译选项。当目录中存在此文件时,直接运行
tsc命令即可自动读取配置。 - 例如,将以下命令:
bash
tsc file1.ts file2.ts --outFile dist/app.js1
- 转换为 tsconfig.json 配置:
json
{
"files": ["file1.ts", "file2.ts"],
"compilerOptions": {
"outFile": "dist/app.js"
}
}1
2
3
4
5
6
2
3
4
5
6
- 然后只需运行:
bash
tsc1
10. 🤔 tsconfig.json 配置文件的作用是什么?
tsconfig.json 是 TypeScript 项目的配置文件,它的主要作用包括:
- 集中管理编译选项:将所有编译配置集中在一个文件中,避免每次编译时都需要输入大量命令行参数
- 项目级配置:为整个 TypeScript 项目提供统一的编译设置,确保团队成员使用相同的编译配置
- 自动化编译:当目录中存在 tsconfig.json 文件时,直接运行
tsc命令即可自动读取配置并编译项目 - IDE 支持:现代编辑器和 IDE 会读取 tsconfig.json 来提供智能提示、错误检查和自动补全等功能
- 构建工具集成:与其他构建工具(如 webpack、gulp 等)集成时,这些工具会参考 tsconfig.json 的配置
通过 tsconfig.json,开发者可以配置包括编译目标、模块系统、输出目录、包含/排除文件、严格模式等在内的各种选项,实现项目级的 TypeScript 编译管理。
11. 🤔 tsconfig.json 和 tsc 之间的关系是?
- 配置与执行的关系:tsconfig.json 是配置文件,定义了编译选项和项目设置;tsc 是执行引擎,读取并应用这些配置来完成实际的编译工作
- 默认读取机制:当运行
tsc命令时,如果当前目录存在 tsconfig.json 文件,tsc 会自动读取其中的配置,无需手动指定编译选项 - 命令行优先级:命令行参数的优先级高于 tsconfig.json 中的配置,可以在运行 tsc 时通过命令行参数覆盖配置文件中的设置
- 项目管理:tsconfig.json 使得 tsc 能够理解项目的整体结构,包括哪些文件需要编译、如何处理模块、使用什么 JavaScript 版本等
- 简化操作:通过 tsconfig.json,开发者只需要运行简单的
tsc命令就能完成复杂的编译任务,而不需要每次都输入长串的命令行参数 - 团队协作:tsconfig.json 确保团队成员使用一致的编译配置,tsc 则保证在不同环境下都能按照相同规则执行编译
总的来说,tsconfig.json 提供配置,tsc 执行编译,两者配合实现了 TypeScript 项目的标准化编译流程。